import { isNumber, isLength } from '@design/core/utils/is-object';
import SCHME_ERROR from '@design/core/constant/schema-error';

function makeLengthValidator(defaultValue) {
  return value => {
    if (!value) {
      return false;
    }
    const stringValue = `${value}`;
    if (stringValue === defaultValue) {
      return true;
    }
    if (isLength(stringValue)) {
      return true;
    }
    return false;
  };
}

function normalizeStyle(error, node) {
  let { style } = node;
  const value = style[error.key];
  switch (error.key) {
    case 'width':
    case 'height':
    case 'minHeight':
    case 'minWidth':
      if (isNumber(value)) {
        style = style.set(error.key, `${value}px`);
      } else {
        style = style.set(error.key, 'auto');
      }
      return node.set('style', style);
    case 'maxWidth':
    case 'maxHeight':
      if (isNumber(value)) {
        style = style.set(error.key, `${value}px`);
      } else {
        style = style.set(error.key, 'initial');
      }
      return node.set('style', style);
    case 'fontSize':    
      if (isNumber(value)) {
        style = style.set(error.key, `${value}px`);
      } else {
        style = style.set(error.key, 'auto');
      }
      return node.set('style', style);
    default:
      return node;
  }
}

export default {
  style: {
    width: makeLengthValidator('auto'),
    height: makeLengthValidator('auto'),
    minHeight: makeLengthValidator('auto'),
    minWidth: makeLengthValidator('auto'),
    maxWidth: makeLengthValidator('initial'),
    maxHeight: makeLengthValidator('initial'),
    fontSize: makeLengthValidator('initial'),
  },
  normalize: (error, node) => {
    switch (error.code) {
      case SCHME_ERROR.STYLE_INVALID:
        return normalizeStyle(error, node);
      default:
        return node;
    }
  },
};
